import email
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Tuple, Dict
from tqdm.notebook import tqdm


class EmailSender:
    def __init__(self, SMTP_HOST, EMAIL_ADDRESS, PASSWORD, flag_template: Dict):
        self.SMTP_HOST = SMTP_HOST
        self.EMAIL_ADDRESS = EMAIL_ADDRESS
        self.PASSWORD = PASSWORD
        self.USER = EMAIL_ADDRESS.split('@')[0]
        self.flag_template = flag_template

    def format_html_template(self, filename, args):
        with open(filename, 'r', encoding='utf-8') as f:
            template = f.read()
        return template.format(*args)

    def make_message(
        self,
        receiver,
        subject_template: str,
        subject_args: Tuple,
        content_flag,
        content_args: Tuple,
    ):
        message = MIMEMultipart('related')
        message['From'] = "{}<{}>".format(self.USER, self.EMAIL_ADDRESS)
        message['To'] = "{}<{}>".format(receiver.split("@")[0], receiver)
        message['Subject'] = subject_template.format(*subject_args)
        mail_body = self.format_html_template(
            self.flag_template[content_flag], content_args)
        part1 = MIMEText(mail_body, _subtype='html', _charset='utf-8')
        message.attach(part1)
        return message

    def send(self, receiver, message):
        try:
            smtpObj = smtplib.SMTP_SSL(self.SMTP_HOST, 465)
            # 连接到服务器
            #smtpObj.connect(self.SMTP_HOST, 465)
            # 登录到服务器
            smtpObj.login(self.USER, self.PASSWORD)
            # 发送
            smtpObj.sendmail(
                self.EMAIL_ADDRESS, receiver, message.as_string())
            # 退出
            smtpObj.quit()
            print('success', receiver)
        except smtplib.SMTPException as e:
            print('error', receiver, e)  # 打印错误


if __name__ == '__main__':
    # 163邮箱服务器地址
    SMTP_HOST = 'smtp.163.com'
    EMAIL_ADDRESS = 'cdac2021@163.com'
    with open('password.txt', 'r') as f:
        PASSWORD = f.read().strip()
    flag_template = {
        0: "html_templates/reject_template.html",
        1: "html_templates/accept_template.html"
    }
    email_sender = EmailSender(
        SMTP_HOST, EMAIL_ADDRESS, PASSWORD, flag_template)
    message = email_sender.make_message(
        receiver="luozn15@qq.com",
        subject_template="2021计算性设计会议摘要#{}: {}",
        subject_args=(1, "接收"),
        content_flag=0,
        content_args=("lzn", "1", "dfasasd")
    )
    email_sender.send("xxxx@qq.com", message)
    print(message.as_string())
